package com.github.dongglin.smart.spring.boot.plus.core.framework.config;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Slf4j
@Component
public class GeneralMetaObjectHandler implements MetaObjectHandler {
    /**
     * 新增时字段填充
     *
     * @param metaObject metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            if (metaObject.hasGetter("guid")) {
                Object guid = metaObject.getValue("guid");
                if (ObjectUtil.isEmpty(guid)) {
                    setFieldValByName("guid", IdWorker.get32UUID(), metaObject);
                }
            }
            if (metaObject.hasSetter("updateTime")) {
                setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
            }
            if (metaObject.hasSetter("createTime")) {
                setFieldValByName("createTime", LocalDateTime.now(), metaObject);
            }
        } catch (Exception e) {
            log.error("GeneralMetaObjectHandler error", e);
        }
    }

    /**
     * 修改时字段 填充
     *
     * @param metaObject metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        try {
            if (metaObject.hasSetter("updateTime")) {
                setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
            }
        } catch (Exception e) {
            log.error("GeneralMetaObjectHandler error", e);
        }
    }
}
